﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace Rel.Expressions
{
  public  class RelResultGroup
    {
      public RelGroup PatternMatched;

      public List<RelResult> Results = new List<RelResult>();

      public static List<RelResultGroup> GetAllExtracts(string src, RelGroup pattern)
      {
          var matches = GetAllMatches(src, pattern);

          List<RelResultGroup> result = new List<RelResultGroup>();

            foreach (RelResultGroup curr in matches)
            {
                RelResultGroup apiece = new RelResultGroup();

                curr.Results.ForEach(o =>
                    {
                        if (o.piece is Extract || o.piece is ExtractCollection)
                        {
                          
                            apiece.Results.Add(o);
                        }
                    });

                result.Add(apiece);
            }

            return result;

      }

      public static List<RelResultGroup> GetAllMatches(string src, RelGroup pattern)
      {
          Regex r = new Regex(pattern.Pattern);

          MatchCollection matches = r.Matches(src);

          List<RelResultGroup> results = new List<RelResultGroup>();

          foreach (Match m in matches)
          {
               RelResultGroup group = new RelResultGroup();
              group.PatternMatched = pattern;
              string[] groupNames = r.GetGroupNames();
              
               foreach (string groupName in groupNames)
               {
                        
                   RelGroup.GroupSearchResult search =  pattern.FindGroup(groupName);

                   if (search == null || search.Type == RelGroup.GroupSearchResult.ResultType.RelGroup)
                   {

                   }
                   else
                   {
                       RelResult aresult = new RelResult();

                       aresult.Match = m.Groups[groupName].Value;
                       aresult.piece = search.BaseResult;

                       if (search.BaseResult is ExtractCollection)
                       {
                           ExtractCollection ec = (ExtractCollection)search.BaseResult;

                           aresult.Collection = ec.PullCollection(aresult.Match);
                           aresult.ContainsCollection = true;
                       }

                       group.Results.Add(aresult);
                   }

                 
               }

                results.Add(group);
          }

          return results;

      }
    }
}
